package com.mr.cai.main.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.cai.mr.lib.utils.LogInfo;
import com.mr.cai.main.R;
import com.mr.cai.main.activity.base.MrCaiBaseActivity;
import com.mr.cai.main.bean.SearchHistoryBean;
import com.mr.cai.main.bean.SearchHotWordBean;
import com.mr.cai.main.httpApi.MrCaiHttpApi;
import com.mr.cai.main.manager.RxjavaSchedulersCompat;
import com.mr.cai.main.parse.SearchHotWordParse;
import com.mr.cai.main.utils.CommonCoreUtil;
import com.mr.cai.main.view.PublicLoadLayout;
import com.mr.cai.main.view.floatview.FlowLayout;

import java.util.ArrayList;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by hai8108 on 16/2/25.
 */
public class MrCaiSearchActivity extends MrCaiBaseActivity {
    private PublicLoadLayout mPublicLayout;
    private View searchHistoryView;
    private View searchRecommendView;
    private View searchRecommendLeftView;
    private TextView searchRecommendTv;
    private FlowLayout searchHistoryFlowLayout, searchRecommendFlowLayout;

    private TextView searchSubmit;
    private EditText searchEditxt;
    private ArrayList<SearchHistoryBean> historyList;

    public static void launch (Activity activity) {
        Intent intent = new Intent(activity, MrCaiSearchActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPublicLayout = CommonCoreUtil.createPage(this, R.layout.activity_search_layout);
        setContentView(mPublicLayout);
        findView();
        initData();
    }

    private void findView () {
        searchSubmit = (TextView) mPublicLayout.findViewById(R.id.mr_cai_search_view);
        searchEditxt = (EditText) mPublicLayout.findViewById(R.id.mr_cai_search);
        CommonCoreUtil.setClickAction(searchSubmit, new Action1() {
            @Override
            public void call (Object o) {
                String keyWord = searchEditxt.getText().toString();
                if (TextUtils.isEmpty(keyWord)) {
                    CommonCoreUtil.showToast(R.string.search_keyword_is_null);
                } else {
                    doSearch(keyWord);
                }
            }
        });
        CommonCoreUtil.setClickAction(mPublicLayout.findViewById(R.id.top_view).findViewById(R.id.pub_top_left)
                , new Action1() {
            @Override
            public void call (Object o) {
                finish();
            }
        });
        ((TextView) mPublicLayout.findViewById(R.id.top_view).findViewById(R.id.pub_top_mid)).setText(R.string
                .mr_cai_search_title);

        searchHistoryView = mPublicLayout.findViewById(R.id.search_history_view);
        searchRecommendView = mPublicLayout.findViewById(R.id.search_recommend_view);
        searchRecommendLeftView = searchRecommendView.findViewById(R.id.search_left_view);
        searchRecommendLeftView.setBackgroundResource(R.color.color_main_yellow);
        searchRecommendTv = (TextView) searchRecommendView.findViewById(R.id.search_tv);
        searchRecommendTv.setText(R.string.search_everybody_want_tag);
        searchHistoryFlowLayout = (FlowLayout) searchHistoryView.findViewById(R.id.search_flowlayout);
        searchRecommendFlowLayout = (FlowLayout) searchRecommendView.findViewById(R.id.search_flowlayout);

    }
    private Subscription searchSub;
    private void initData () {
        rx.Observable.just("findhistory").map(new Func1<String,
                ArrayList<SearchHistoryBean>>
                () {
            @Override
            public ArrayList<SearchHistoryBean> call (String s) {
                historyList = (ArrayList<SearchHistoryBean>) SearchHistoryBean.findDataAll();
                return historyList;
            }
        }).filter(new Func1<ArrayList<SearchHistoryBean>, Boolean>() {
            @Override
            public Boolean call (ArrayList<SearchHistoryBean> searchHistoryBeans) {
                if (searchHistoryBeans == null || searchHistoryBeans.size() <= 0) {
                    LogInfo.log("haitian", "false");
                    return false;
                } else {
                    LogInfo.log("haitian", "true");
                    return true;
                }
            }
        }).compose(RxjavaSchedulersCompat.<ArrayList<SearchHistoryBean>>applyIoSchedulers())
        .subscribe(new Action1<ArrayList<SearchHistoryBean>>() {
            @Override
            public void call (ArrayList<SearchHistoryBean> searchHistoryBeans) {
                searchHistoryFlowLayout.setVisibility(View.VISIBLE);
                updateHistoryLayout(searchHistoryFlowLayout, searchHistoryBeans);
            }
        });
        Observable<SearchHotWordBean> searchObservable = MrCaiHttpApi.requestSearchHotWordList(new
                SearchHotWordParse());
        searchSub = searchObservable.observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call () {
                        mPublicLayout.loading(true);
                    }
                })
                .subscribe(new Subscriber<SearchHotWordBean>() {
                    @Override
                    public void onCompleted () {
                        mPublicLayout.finish();
                    }
                    @Override
                    public void onError (Throwable e) {
                    }
                    @Override
                    public void onNext (SearchHotWordBean mSearchHotWordBean) {
                        if(mSearchHotWordBean.isResult() && mSearchHotWordBean.getCode() == 1){
                            searchRecommendFlowLayout.setVisibility(View.VISIBLE);
                            String[] split = mSearchHotWordBean.getData().split("\\|");
                            SearchHistoryBean mHBean = null;
                            ArrayList<SearchHistoryBean> list = new ArrayList<SearchHistoryBean>();
                            for (int i=0; i< split.length; i++){
                                mHBean = new SearchHistoryBean();
                                mHBean.setKeyWord(split[i]);
                                LogInfo.log("haitian", "split[i]="+split[i]);
                                mHBean.setAddTime(System.currentTimeMillis());
                                list.add(mHBean);
                            }
                            updateHistoryLayout(searchRecommendFlowLayout, list);
                        } else {
                        }
                    }
                });
    }
    @Override
    public void onDestroy () {
        super.onDestroy();
        CommonCoreUtil.hideSoftInput(searchEditxt);
        if (searchSub != null) {
            searchSub.unsubscribe();
            searchSub = null;
        }
    }
    private void updateHistoryLayout (FlowLayout mFlowLayout, ArrayList<SearchHistoryBean>
            searchList) {
        mFlowLayout.removeAllViewsInLayout();
        View view = null;
        for (SearchHistoryBean mBean : searchList) {
            view = createSearchTagView(mBean);
            mFlowLayout.addView(view);
        }
    }

    private View createSearchTagView (final SearchHistoryBean searchHistoryBean) {
        final View view = LayoutInflater.from(this).inflate(R.layout.mr_cai_search_txt_tag_layout, null);
        TextView keyWordView = (TextView) view.findViewById(R.id.search_tag_txt_view);
        keyWordView.setText(searchHistoryBean.getKeyWord());
        keyWordView.setTag(searchHistoryBean.getKeyWord());
        keyWordView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick (View v) {
                String tag = (String) v.getTag();
                CommonCoreUtil.showToast(tag);
            }
        });
        return view;
    }

    private void doSearch (String keyWord) {
        SearchHistoryBean mBean = new SearchHistoryBean();
        mBean.setKeyWord(keyWord);
        mBean.setAddTime(System.currentTimeMillis());
        SearchHistoryBean.saveData(mBean);
    }
}
